package net.maku.im.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.PageResult;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.im.constant.ImConstant;
import net.maku.im.convert.ImPrivateMessageConvert;
import net.maku.im.dao.ImPrivateMessageDao;
import net.maku.im.dto.ImPrivateMessageQueryDTO;
import net.maku.im.entity.ImPrivateMessageEntity;
import net.maku.im.service.ImPrivateMessageService;
import net.maku.im.vo.ImPrivateMessageVO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 私聊消息
 *
 * @author Blue
 * @since 1.0.0 2024-07-19
 */

@Service
@AllArgsConstructor
@DS(ImConstant.DS_IM_PLATFORM)
public class ImPrivateMessageServiceImpl extends BaseServiceImpl<ImPrivateMessageDao, ImPrivateMessageEntity>
    implements ImPrivateMessageService {

    @Override
    public PageResult<ImPrivateMessageVO> page(ImPrivateMessageQueryDTO query) {
        LambdaQueryWrapper<ImPrivateMessageEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(!Objects.isNull(query.getSendId()), ImPrivateMessageEntity::getSendId, query.getSendId());
        wrapper.eq(!Objects.isNull(query.getRecvId()), ImPrivateMessageEntity::getRecvId, query.getRecvId());
        wrapper.eq(!Objects.isNull(query.getType()), ImPrivateMessageEntity::getType, query.getType());
        wrapper.eq(!Objects.isNull(query.getStatus()), ImPrivateMessageEntity::getStatus, query.getStatus());
        wrapper.like(StrUtil.isNotEmpty(query.getContent()), ImPrivateMessageEntity::getContent, query.getContent());
        if (CollectionUtil.isNotEmpty(query.getSendTime()) && query.getSendTime().size() > 1) {
            wrapper.between(ImPrivateMessageEntity::getSendTime, query.getSendTime().get(0),
                query.getSendTime().get(1));
        }
        wrapper.orderByDesc(ImPrivateMessageEntity::getId);
        IPage<ImPrivateMessageEntity> page = baseMapper.selectPage(getPage(query), wrapper);
        List<ImPrivateMessageVO> vos = ImPrivateMessageConvert.INSTANCE.convertList(page.getRecords());
        return new PageResult<>(vos, page.getTotal());
    }

    @Override
    public ImPrivateMessageVO info(Long id) {
        ImPrivateMessageEntity message = this.getById(id);
        return ImPrivateMessageConvert.INSTANCE.convert(message);
    }
}